package org.lex.net.proxy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.lex.net.Password;
import org.lex.utils.Codec;
import org.lex.utils.SystemProperties;


public class ProxyServerUtils {
	public static void setSystemDefault(ProxyServer ps) {
		// System default
		System.setProperty("socksProxyHost", ps.getHost());
		System.setProperty("socksProxyPort", Integer.toString(ps.getPort()));
		final Password pw = ps.getPassword();
		Authenticator a = new Authenticator() {
			PasswordAuthentication pa = new PasswordAuthentication(pw.getUserName(), pw.getPassword());

			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return pa;
			}
		};
		Authenticator.setDefault(a);
	}

	public static void exportPlain(Collection<ProxyServer> servers, Writer out) throws IOException {
		if (null == servers || servers.isEmpty())
			return;
		String sep = SystemProperties.lineSeparator();
		for (ProxyServer s : servers) {
			out.write(encode(s));
			out.write(sep);
		}
		out.flush();
	}

	public static List<ProxyServer> importPlain(Reader in) throws IOException {
		ArrayList<ProxyServer> list = new ArrayList<ProxyServer>();
		BufferedReader reader = new BufferedReader(in);
		while (true) {
			String line = reader.readLine();
			if (null == line)
				break;
			ProxyServer s = decode(line);
			if (null != s)
				list.add(s);
		}
		return list;
	}

	public static String encode(ProxyServer server) {
		return server.getName() + " " + Codec.encodeProxy(server.getProxy());
	}

	public static ProxyServer decode(String input) {
		if (null == input)
			return null;
		input = input.trim();
		if (input.isEmpty())
			return null;
		int index = input.lastIndexOf(' ');
		if (-1 == index)
			return null;
		return new ProxyServer(input.substring(0, index), Codec.decodeProxy(input.substring(index + 1)));
	}

	private ProxyServerUtils() {
	}
}
